package com.wk.portal.service.impl;

import com.alibaba.fastjson.JSON;
import com.wk.common.constant.RedisKey;
import com.wk.pms.entity.Category;
import com.wk.pms.feign.CategoryFeign;
import com.wk.pms.vo.CategoryVO;
import com.wk.portal.annotion.GmallCache;
import com.wk.portal.service.PortalService;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PortalServiceImpl implements PortalService {

    @Autowired
    private CategoryFeign categoryFeign;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public List<Category> queryLv1Category() {
        return categoryFeign.queryCategoriesByPidOrLevel(1, null).getData();
    }

    @GmallCache(RedisKey.PORTAL_CATEGORY)
    @Override
    public List<CategoryVO> queryByPrentId(Long pid) {



        //使用redisson提供的分布式锁防止缓存击穿
        RLock lock = redissonClient.getLock("categoryLock" + pid);
        //锁定对应的pid
        lock.lock();

        //判断Redis中是否存在对应数据
        String categorys2 = redisTemplate.boundValueOps(RedisKey.PORTAL_CATEGORY + pid).get();

        //如果存在，将json转成集合后返回
        if (StringUtils.isNotBlank(categorys2)) {
            //缓存中只要有数据就释放锁并返回
            lock.unlock();
            return JSON.parseArray(categorys2,CategoryVO.class);
        }

        //不存在则查询数据库
        List<CategoryVO> list = categoryFeign.queryByPid(pid).getData();

        //将数据库中的数据放入到缓存中
        redisTemplate.boundValueOps(RedisKey.PORTAL_CATEGORY + pid).set(JSON.toJSONString(list));

        //释放所
        lock.unlock();

        return list;
    }
}
